package jwtx

import (
	"context"
	"fmt"

	"encoding/json"
	"github.com/golang-jwt/jwt"
	"github.com/zeromicro/go-zero/core/logx"
)

func GetToken(secretKey string, iat, seconds, uid int64, tenantId int32, OrganizationID int64) (string, error) {
	claims := make(jwt.MapClaims)
	claims["expend"] = iat + seconds
	claims["iat"] = iat
	claims["userId"] = uid
	claims["organizationId"] = OrganizationID
	claims["tenantId"] = tenantId
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

func GetUserId(ctx context.Context) int64 {
	var uid int64
	if jsonUid, ok := ctx.Value("userId").(json.Number); ok {
		if int64Uid, err := jsonUid.Int64(); err == nil {
			uid = int64Uid
		} else {
			logx.WithContext(ctx).Errorf("GetUidFromCtx err : %+v", err)
		}
	}
	return uid
}

func GetUserTenantId(ctx context.Context) int32 {
	var TenantId int32
	if jsonTenantId, ok := ctx.Value("tenantId").(json.Number); ok {
		if int64TenantId, err := jsonTenantId.Int64(); err == nil {
			TenantId = int32(int64TenantId)
		} else {
			logx.WithContext(ctx).Errorf("GetTenantIdFromCtx err : %+v", err)
		}
	}
	return TenantId
}
func GetUserTenantId64(ctx context.Context) int64 {
	var TenantId int64
	fmt.Print("ctx:", ctx)
	if jsonTenantId, ok := ctx.Value("tenantId").(json.Number); ok {
		if int64TenantId, err := jsonTenantId.Int64(); err == nil {
			TenantId = int64TenantId
		} else {
			logx.WithContext(ctx).Errorf("GetTenantIdFromCtx err : %+v", err)
		}
	}
	return TenantId
}

// 取用户的织组ID

func GetUseOrganizationId(ctx context.Context) int64 {
	var organizationId int64
	if jsonTenantId, ok := ctx.Value("organizationId").(json.Number); ok {
		if int64TenantId, err := jsonTenantId.Int64(); err == nil {
			organizationId = int64TenantId
		} else {
			logx.WithContext(ctx).Errorf("GetTenantIdFromCtx err : %+v", err)
		}
	}
	return organizationId
}
